<template>
  <div class="app-container">
    <!-- todo 设置宽度 -->
    <el-form :model="queryParams" ref="queryForm" size="mini" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="数据源名称" prop="datasourceName">
        <el-input
          v-model="queryParams.datasourceName"
          placeholder="请输入数据源名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="数据源类型" prop="datasourceType">
        <el-select v-model="queryParams.datasourceType" placeholder="请选择数据源类型" clearable>
          <el-option
            v-for="dict in dict.type.data_datasource_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="数据库名" prop="databaseName">
        <el-input
          v-model="queryParams.databaseName"
          placeholder="请输入数据库名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['data:datasource:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['data:datasource:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="datasourceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="数据源名称" align="center" prop="datasourceName" />
      <el-table-column label="数据源类型" align="center" prop="datasourceType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.data_datasource_type" :value="scope.row.datasourceType"/>
        </template>
      </el-table-column>
      <el-table-column label="驱动类型" align="center" prop="driveType" />
      <el-table-column label="服务器地址" align="center" prop="serverAddr" />
      <el-table-column label="端口" align="center" prop="port" />
      <el-table-column label="数据库名" align="center" prop="databaseName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['data:datasource:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['data:datasource:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改数据源表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="数据源名称" prop="datasourceName">
          <el-input v-model="form.datasourceName" placeholder="请输入数据源名称" />
        </el-form-item>
        <el-form-item label="数据源类型" prop="datasourceType">
          <el-select v-model="form.datasourceType" placeholder="请选择数据源类型">
            <el-option
              v-for="dict in dict.type.data_datasource_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="驱动类型" prop="driveType">
          <el-input v-model="form.driveType"  placeholder="请输入驱动类型" />
        </el-form-item>
        <el-form-item label="服务器地址" prop="serverAddr">
          <el-input v-model="form.serverAddr" placeholder="请输入服务器地址" />
        </el-form-item>
        <el-form-item label="端口" prop="port">
          <el-input v-model="form.port" placeholder="请输入端口" />
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-row>
            <el-col :span="12">
              <el-input v-model="form.password" placeholder="请输入密码" type="password"/>
            </el-col>
            <el-col :span="12">
              <el-button @click="changePassword" >编辑</el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="数据库名" prop="databaseName">
          <el-input v-model="form.databaseName" placeholder="请输入数据库名" />
        </el-form-item>
        <el-form-item label="扩展连接串" prop="extLinkStr">
          <el-input v-model="form.extLinkStr" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
        <el-button @click="testConnect">测试连接</el-button>
      </div>

    </el-dialog>
  </div>
</template>

<script>
import { listDatasource, getDatasource, delDatasource, addDatasource, updateDatasource,testDatasource } 
from "@/api/data/datasource";
import AES from 'crypto-js';



export default {
  name: "Datasource",
  dicts: ['data_datasource_type'],
  data() {
    return {
      //十六位十六进制数作为密钥
       key: AES.enc.Utf8.parse('0123456789ASDFGH'),
      //十六位十六进制数作为密钥偏移量
       iv: AES.enc.Utf8.parse('ASDFGH0123456789'), 
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 数据源表表格数据
      datasourceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        datasourceName: null,
        datasourceType: null,
        driveType: null,
        serverAddr: null,
        port: null,
        userName: null,
        password: null,
        databaseName: null,
        extLinkStr: null,
        createId: null,
        updateId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
          datasourceName: [
            { required: true, message: "数据源名称不能为空", trigger: "blur" }
          ],
          datasourceType: [
            { required: true, message: "数据源类型不能为空", trigger: "change" }
          ],
          driveType: [
            { required: true, message: "驱动类型不能为空", trigger: "blur"}
          ],
          serverAddr: [
            { required: true, message: "服务器地址不能为空", trigger: "blur" }
          ],
          port: [
            { required: true, message: "端口不能为空", trigger: "blur" }
          ],
          userName: [
            { required: true, message: "用户名不能为空", trigger: "blur" }
          ],
          password: [
            { required: true, message: "密码不能为空", trigger: "blur" }
          ],
          databaseName: [
            { required: true, message: "数据库名不能为空", trigger: "blur" }
          ],
          extLinkStr: [
            // { required: true, message: "扩展连接串不能为空", trigger: "blur" }
          ]
        }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询数据源表列表 */
    getList() {
      this.loading = true;
      listDatasource(this.queryParams).then(response => {
        this.datasourceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        datasourceId: null,
        datasourceName: null,
        datasourceType: null,
        driveType: null,
        serverAddr: null,
        port: null,
        userName: null,
        password: null,
        databaseName: null,
        extLinkStr: null,
        createId: null,
        createTime: null,
        updateId: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.datasourceId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加数据源表";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const datasourceId = row.datasourceId || this.ids
      getDatasource(datasourceId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改数据源表";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          //this.form.password = this.encryptPassword(this.form.password);
          if (this.form.datasourceId != null) {
            updateDatasource(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDatasource(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 加密密码
    encryptPassword(password) {
      const src = AES.enc.Utf8.parse(password);
      const encrypted = AES.AES.encrypt(
          src,
          this.key,
          {
              iv: this.iv,
              mode: AES.mode.CBC,
              padding: AES.pad.Pkcs7
          });
      return encrypted.ciphertext.toString().toUpperCase();
    },
    // 解密密码
    decrypt(password){
      const encryptedHexStr = AES.enc.Hex.parse(password);
      const src = AES.enc.Base64.stringify(encryptedHexStr);
      const decrypt = AES.AES.decrypt(
          src,
          this.key,
          {
              iv: this.iv,
              mode: AES.mode.CBC,
              padding: AES.pad.Pkcs7
          });
      const decryptedStr = decrypt.toString(AES.enc.Utf8);
      return decryptedStr.toString();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const datasourceIds = row.datasourceId || this.ids;
      this.$modal.confirm('是否确认删除此数据项？').then(function() {
        return delDatasource(datasourceIds);
      }).then(response  => {
        this.getList();
        if (response.status === 200) {
          this.$modal.msgSuccess(response.message || "删除成功");
        } else {
          this.$modal.msgError(response.message || "删除失败");
        }
      }).catch(() => {});
    },
    // /** 导出按钮操作 */
    // handleExport() {
    //   this.download('data/datasource/export', {
    //     ...this.queryParams
    //   }, `datasource_${new Date().getTime()}.xlsx`)
    // },
    /**
     * 测试连接操作
     */
    testConnect(){
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(!this.form.datasourceId){
            this.form.password = this.encryptPassword(this.form.password);
          }
            testDatasource(this.form).then(response => {
              if (response.code === 200) {
                this.$modal.msgSuccess("测试连接成功");
              } else {
                this.$modal.msgError("测试连接失败");
              }
          }).catch(error => {
              this.$modal.msgError("测试连接失败, 错误信息：" + error.message); // 当接口请求失败时显示错误提示
          });
          // this.form.password = this.decrypt(this.form.password);
        }
      });
    },
    changePassword(){
      this.form.password = null;
    }
  }
};
</script>
